<?php

namespace addons\helper\controller\wxapp\general;

use think\Exception;

use app\common\model\Config as ConfigModel;
use addons\helper\controller\wxapp\Base;

class Config extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Config;
    }
    /**
     * 首页
     */
    public function index()
    {
        $siteList  = [];
        $groupList = ConfigModel::getGroupList();
        foreach ($groupList as $k => $v) {
            $siteList[$k]['name']  = $k;
            $siteList[$k]['title'] = $v;
            $siteList[$k]['list']  = [];
        }
        foreach (ConfigModel::all() as $k => $v) {
            if (!isset($siteList[$v['group']])) {
                continue;
            }
            $value = $v->toArray();
            $value['title']       = __($value['title']);
            $value['value_title'] = $value['value'];
            // 选项格式化
            if ($value['value'] && in_array($value['type'], ['selects', 'checkbox'])) {
                $value['value'] = explode(',', $value['value']);
                $value['value_title'] = [];
                foreach ($value['value'] as $vv) {
                    $value['value_title'][] = json_decode($value['content'], true)[$vv];
                }
            }
            if ($value['value'] && in_array($value['type'], ['radio', 'select'])) {
                $value['value_title'] = isset(json_decode($value['content'], true)[$value['value']]) ?json_decode($value['content'], true)[$value['value']] : '请重新设置';
            }
            if ($value['type'] === 'switch') {
                $value['value_title'] = $value['value'] ? '打开' : '关闭';
            }
            $value['content']             = json_decode($value['content'], true);
            $value['tip']                 = htmlspecialchars($value['tip']);
            $siteList[$v['group']]['list'][] = $value;
        }
        $data = [
            'siteList'  => $siteList,
            'typeList'  => ConfigModel::getTypeList(),
            'ruleList'  => ConfigModel::getRegexList(),
            'groupList' => ConfigModel::getGroupList()
        ];
        $this->success('系统配置数据获取成功', $data);
    }
    /**
     * 添加
     */
    public function add()
    {
        $params = $this->request->post('', [], 'trim');

        if (!$params) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $config = ConfigModel::get(['name' => $params['name']]);
        if ($config) {
            $this->error('变量名已存在');
        }

        foreach ($params as $k => &$v) {
            $v = is_array($v) ? implode(',', $v) : $v;
        }
        if (in_array($params['type'], ['select', 'selects', 'checkbox', 'radio'])) {
            $params['content'] = json_encode(ConfigModel::decode($params['content'],"\n"), JSON_UNESCAPED_UNICODE);
        } else {
            $params['content'] = '';
        }

        try {
            $result = ConfigModel::create($params);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        if ($result !== false) {
            try {
                $this->refreshFile();
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('添加成功');
        } else {
            $this->error(ConfigModel::getError());
        }
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $data = $this->request->post();
        try {
            $config = ConfigModel::get($data['id']);
            if (in_array($config['type'], ['selects', 'checkbox'])) {
                $data['value'] = implode(',', $data['value']);
            }
            $config->value = $data['value'];
            $config->allowField(true)->save();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        try {
            $this->refreshFile();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('修改成功');
    }
    /**
     * 删除
     * @return void
     */
    public function del()
    {
        $id = $this->request->post('id');
        if ($id < 18) {
            $this->error('该配置项禁止删除');
        }
        $config = ConfigModel::get($id);
        if ($config) {
            try {
                $config->delete();
                $this->refreshFile();
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('删除成功');
        } else {
            $this->error(__('Invalid parameters'));
        }
    }
    /**
     * 刷新配置文件
     */
    protected function refreshFile()
    {
        $config = [];
        foreach ($this->model->all() as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array) json_decode($value['value'], true);
            }
            $config[$value['name']] = $value['value'];
        }
        file_put_contents(
            APP_PATH . 'extra' . DS . 'site.php',
            '<?php' . "\n\nreturn " . var_export($config, true) . ';'
        );
    }
}
